#!/usr/bin/env python
#coding=utf-8
#import models
import template
import functools
import models
import os

def safeint(x, default=0):
    """ always base=10 """

    if not x:
        return default

    try:
        if x.startswith('/'):
            x = x[1:]
        n = int(x)
    except ValueError:
        n = default
    return n


#Now supports GAE only.
def get_paging_links(results, prev, next, start_index):
    links = dict(next=0, prev=0, last=0)

    if prev:
        links['prev'] = prev.index
    if next:
        links['next'] = next.index

    return links

def render(dir, env=None):
    return functools.partial(template.template_file, dirs=[dir], env=env)


## from http://www.djangosnippets.org/snippets/821/
def send_to(renderer, template):
    """
        If view doesn't return dict then decorator simply returns output.
        Additionally view can return two-tuple, which must contain dict as first
        element and string with template name as second. This string will
        override template name, given as parameter

        Parameters:
         - template: template name to use
    """

    def sender(func):
        def wrapper(*args, **kw):
            output = func(*args, **kw)
            if isinstance(output, (list, tuple)):
                return renderer(output[1], vars=output[0])
            elif isinstance(output, dict):
                return renderer(template, vars=output)
            return output

        return wrapper
    return sender


def get_current_theme():
    return models.get_blog_config().theme_name


def scan_themes():
    themes = []

    for d in os.listdir('./themes'):
         if os.path.isdir(os.path.join(os.getcwd(), 'themes', d)):
             themes.append(d)

    return themes
